package com.alvis.media;

import org.junit.Test;
import java.io.*;
import java.util.Properties;

public class Test03 {
    
    @Test
    public void testPy() {
        try {
            // 1. 加载配置文件
            Properties properties = new Properties();
            // 配置文件放在resources目录下，使用类加载器读取
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream("python-config.properties");
            if (inputStream == null) {
                throw new FileNotFoundException("配置文件 python-config.properties 未找到");
            }
            properties.load(inputStream);
            
            // 2. 从配置文件获取路径
            String pythonInterpreter = properties.getProperty("python.interpreter.path");
            String pythonScript = properties.getProperty("python.script.path");
            
            // 3. 定义命令数组
            String[] cmd = {pythonInterpreter, pythonScript};

            // 4. 启动进程执行命令
            Process process = new ProcessBuilder(cmd)
                    .redirectErrorStream(true)  // 合并错误流到输入流
                    .start();

            // 5. 读取Python的输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Python输出：" + line);
            }

            // 6. 等待脚本执行完成
            int exitCode = process.waitFor();
            System.out.println("脚本执行结束，退出码：" + exitCode);
            
            // 关闭资源
            inputStream.close();
            reader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
    